package com.example.network;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.network.databinding.ActivityMainBinding;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;

    public final static String BAIDU_URL = "https://www.baidu.com";
    // message的标识
    public final static int WEATHER_ID = 1;
    // 天气预报接口地址
    public final static String WEATHER_URL = "http://apis.juhe.cn/simpleWeather/query";
    // 天气预报接口请求Key
    public static String API_KEY = "8558d229e191278eaef1a355631621e4";

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            Log.i("MainActivity", msg.toString());
            if (msg.what == WEATHER_ID) {
                final Weather weather = (Weather) msg.obj;
                if (weather.getErrorCode() == 0) {
                    Toast.makeText(MainActivity.this, weather.getReason(), Toast.LENGTH_SHORT).show();

                    String result = "\n当前温度：" + weather.getResult().getRealtime().getTemperature() +
                            "\n当前天气：" + weather.getResult().getRealtime().getInfo() +
                            "\n空气质量：" + weather.getResult().getRealtime().getAqi() +
                            "\n明天天气：" + weather.getResult().getFuture().get(0).getWeather() +
                            "\n明天温度：" + weather.getResult().getFuture().get(0).getTemperature() +
                            "\n后天天气：" + weather.getResult().getFuture().get(1).getWeather() +
                            "\n后天温度：" + weather.getResult().getFuture().get(1).getTemperature();
                    binding.tvResponse.setText(result);
                }
            } else if (msg.what == WTHR_ID) {
                Wthr wthr = (Wthr) msg.obj;
                if (wthr.getDesc().equals("OK")) {
                    String result = "\n当前温度：" + wthr.getData().getWendu() +
                            "\n当前天气：" + wthr.getData().getForecast().get(0).getType() +
                            "\n明天天气：" + wthr.getData().getForecast().get(1).getType() +
                            "\n明天高温：" + wthr.getData().getForecast().get(1).getHigh() +
                            "\n明天低温：" + wthr.getData().getForecast().get(1).getLow() +
                            "\n后天天气：" + wthr.getData().getForecast().get(2).getType() +
                            "\n后天高温：" + wthr.getData().getForecast().get(2).getHigh() +
                            "\n后天低温：" + wthr.getData().getForecast().get(2).getLow();
                    binding.tvResponse.setText(result);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.btnRequest.setOnClickListener(v -> new Thread(() -> {
            // 获取网页文本
            String result = MainActivity.this.doGet("https://www.baidu.com", "");
            if (!TextUtils.isEmpty(result)) {
                // 显示在文本框中
                MainActivity.this.runOnUiThread(() -> binding.tvResponse.setText(result));
//                            binding.tvResponse.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    binding.tvResponse.setText(result);
//                                }
//                            });
            }
        }).start());

        binding.btnWeather.setOnClickListener(v -> {
            String city = binding.etCity.getText().toString();
            if (!TextUtils.isEmpty(city)) {
                getWeather1(city);
            } else {
                Toast.makeText(MainActivity.this, "请输入城市名称", Toast.LENGTH_SHORT).show();
            }
        });

        binding.btnApi.setOnClickListener(v -> {
            // get请求
//            new Thread(() -> {
//                String result = doGet("http://10.0.2.2:8080/android/hello", "");
//                if (!TextUtils.isEmpty(result)) {
//                    MainActivity.this.runOnUiThread(() -> binding.tvResponse.setText(result));
//                } else {
//                    MainActivity.this.runOnUiThread(() -> binding.tvResponse.setText("no data"));
//                }
//            }).start();

            // post请求
            login("http://10.0.2.2:8080/android/login", new User("android", "111111"));
        });
    }

    private static final int WTHR_ID = 10;
    private static final String WTHR_URL = "http://wthrcdn.etouch.cn/weather_mini";

    private void getWeather1(String city) {
        new Thread(() -> {
            // 组合请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("city", city);
            // 获取天气数据
            String result = doGet(WTHR_URL, urlencode(params));
            if (!TextUtils.isEmpty(result)) {
                // 将JSON数据转为Java对象
                Wthr wthr = new Gson().fromJson(result, Wthr.class);
                // handler发送消息
                Message msg = handler.obtainMessage();
                msg.what = WTHR_ID;
                msg.obj = wthr;
                handler.sendMessage(msg);
            }
        }).start();
    }


    private void login(String url, User user) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Gson gson = new Gson();
                String json = gson.toJson(user);
                final String result = doPost(url, json);
                if (!TextUtils.isEmpty(result)) {
                    MainActivity.this.runOnUiThread(() -> binding.tvResponse.setText(result));
                }
            }
        }).start();
    }

    private void getWeather(String city) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 组合请求参数
                Map<String, Object> params = new HashMap<>();
                params.put("city", city);
                params.put("key", API_KEY);
                // 获取天气数据
                String result = doGet(WEATHER_URL, urlencode(params));
                if (!TextUtils.isEmpty(result) && !result.contains("超过每日可允许请求次数")) {
                    // 将JSON数据转为Java对象
                    // 1. JSONObject
                    Weather weather = parseJson(result);

                    // 2. Gson
                    //   Gson gson = new Gson();
                    //  Weather weather = gson.fromJson(result, Weather.class);

                    // handler发送消息
                    Message msg = handler.obtainMessage();
                    msg.what = WEATHER_ID;
                    msg.obj = weather;
                    handler.sendMessage(msg);
                } else {
                    MainActivity.this.runOnUiThread(() -> {
                        binding.tvResponse.setText(result);
                    });
                }
            }
        }).start();
    }

    private Weather parseJson(String result) {
        Weather weather = new Weather();
        try {
            // 1. 第一层
            JSONObject jsonObj = new JSONObject(result);
            weather.setReason(jsonObj.getString("reason"));
            weather.setErrorCode(jsonObj.getInt("error_code"));
            // 2. 第二层
            JSONObject resultObj = jsonObj.getJSONObject("result");
            // 3. 第三层
            JSONObject realtimeObj = resultObj.getJSONObject("realtime");
            Weather.Result.Realtime realtime = new Weather.Result.Realtime();
            realtime.setTemperature(realtimeObj.getString("temperature"));
            realtime.setInfo(realtimeObj.getString("info"));
            realtime.setAqi(realtimeObj.getString("aqi"));
            // 3. 第三层
            final JSONArray futureArray = resultObj.getJSONArray("future");
            List<Weather.Result.Future> futures = new ArrayList<>();
            for (int i = 0; i < futureArray.length(); i++) {
                final JSONObject obj = futureArray.getJSONObject(i);
                Weather.Result.Future future = new Weather.Result.Future();
                future.setWeather(obj.getString("weather"));
                future.setTemperature(obj.getString("temperature"));
                futures.add(future);
            }
            Weather.Result weatherResult = new Weather.Result();
            weatherResult.setCity(resultObj.getString("city"));
            weatherResult.setFuture(futures);
            weatherResult.setRealtime(realtime);

            weather.setResult(weatherResult);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return weather;
    }

    /**
     * 将map类型转为请求参数型
     *
     * @param data Map类型参数
     * @return 请求字符串
     * http://apis.juhe.cn/simpleWeather/query?city=%E5%8D%97%E4%BA%AC&&key=
     */
    private static String urlencode(Map<String, ?> data) {
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, ?> entry : data.entrySet()) {
            try {
                builder.append(entry.getKey()).append("=")
                        .append(URLEncoder.encode(entry.getValue() + "", "UTF-8"))
                        .append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String result = builder.toString();
        return result.substring(0, result.lastIndexOf("&"));
    }

    /**
     * GET方式的网络请求
     *
     * @param httpUrl    网址
     * @param queryParam 请求字符串，格式为key1=value1&key2=value2
     * @return 服务器端返回的字符串
     */
    private String doGet(String httpUrl, String queryParam) {
        String result = null; // 返回字符串
        try {
            if (!TextUtils.isEmpty(queryParam)) {
                httpUrl += "?" + queryParam;
            }
            URL url = new URL(httpUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置请求方法、连接超时和读超时时间
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            // 获取请求返回的响应输入流
            InputStream is = conn.getInputStream();
            // 使用Java的BufferedReader读取响应的文本内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line).append(System.getProperty("line.separator"));
            }
            result = buffer.toString();
            // 关闭资源、断开连接
            reader.close();
            is.close();
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return result;
    }

    /**
     * POST方式的网络请求
     *
     * @param httpUrl    网址
     * @param queryParam 请求字符串，格式为json字符串
     * @return 服务器端返回的字符串
     */
    private String doPost(@NonNull String httpUrl, @NonNull String queryParam) {
        String result = null; // 返回字符串
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置请求方法、连接超时和读超时时间
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestProperty("content-type", "application/json; utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // post方式发送参数
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
            writer.write(queryParam);
            writer.flush();
            writer.close();
            os.close();

            // 获取输入流
            InputStream is = conn.getInputStream();
            // 应用输入流读取网页脚本
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line).append(System.getProperty("line.separator"));
            }
            result = buffer.toString();
            // 关闭资源、断开连接
            reader.close();
            is.close();
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private void getMessage(String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = doGet(url, "");
                if (!TextUtils.isEmpty(result)) {
                    runOnUiThread(() -> binding.tvResponse.setText(result));

//                    Gson gson = new Gson();
//                    final ResponseEntity responseEntity = gson.fromJson(result, ResponseEntity.class);
//                    if (responseEntity != null && responseEntity.getCode() == 200) {
//                        runOnUiThread(() -> binding.tvResponse.setText((String) responseEntity.getData()));
//                    }
                } else {
                    runOnUiThread(() -> binding.tvResponse.setText("no data"));
                }
            }
        }).start();
    }

}